<script lang="ts" setup>
import {ref, onMounted, markRaw, withDefaults, defineProps} from "vue";
import {ElMessageBox} from "element-plus";
import {
  deleteProtocolItemById,
  getAllProtocolList,
  saveOrUpdateProtocolItem
} from "@/api/toolLibs/protocolLib";
import {message} from "@/utils/ElmessasgeUtils";
import type {ProtocolItemDO} from "@/type/toolLibs/protocol";
import {Delete} from "@element-plus/icons-vue";
import {
  getCategoryName, updateCategoryList, searchForm, handleOpenProtocolParse, handleOpenProtocolEdit
} from "@/views/ToolLibs/ProtocolViewer/protocol";
import {toHex} from "@/utils/StringUtils";


const props = withDefaults(
    defineProps<{
      showBtn: boolean
    }>(),
    {
      showBtn: true
    })

const emit = defineEmits<{
  (e: 'select', protocolId: string): void
}>()


// 原始协议项数据
const protocolItems = ref<ProtocolItemDO[]>([]);

// 分页相关数据
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);


// 分页查询协议列表
async function fetchProtocolList() {
  loading.value = true;
  try {

    // 构建分页请求参数
    let baseParams = {
      // 分页参数
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      // 查询条件
      protocolName: searchForm.protocolName,
      createNickName: searchForm.createNickName,
      createTimeBegin: searchForm.createTimeBegin,
      createTimeEnd: searchForm.createTimeEnd,
      code: searchForm.code,
      msgType: searchForm.msgType,
    };
    let params: any;
    if (searchForm.categories && searchForm.categories.length > 0) {
      if (searchForm.category == '0') {
        searchForm.categories.push('0');
      }

      params = {...baseParams, categories: searchForm.categories};
    } else {
      params = {...baseParams, category: searchForm.category};
    }

    let protocolDataRes = await getAllProtocolList(params);

    if (protocolDataRes.data.code == 200) {
      let responseData = protocolDataRes.data.data;
      console.log("后端数据", responseData);

      // 从分页对象中提取数据列表
      let data: ProtocolItemDO[] = Array.isArray(responseData.records) ? responseData.records : [];
      // 更新总数，确保是数字类型，并且如果records有数据但total为0，则使用records.length
      total.value = Number(responseData.total) || data.length || 0;

      // 保存原始协议项数据
      protocolItems.value = data;


    } else {
      message("获取协议列表失败", 'error');
      total.value = 0;
    }
  } catch (error) {
    message("获取协议列表失败", 'error');
    total.value = 0;
  } finally {
    loading.value = false;
  }
}


/**
 * 选择协议
 */
function handleSelectProtocol(protocol: ProtocolItemDO) {
  emit('select', protocol.id)
}

function handleSizeChange(size: number) {
  pageSize.value = size;
  currentPage.value = 1;

  // 重新获取数据
  fetchProtocolList();
}
// 分页变化处理
const handlePageChange = (page: number, size: number) => {
  currentPage.value = page;
  if (size) {
    pageSize.value = size;
  }
  // 重新获取数据
  fetchProtocolList();
};


// 删除协议
const deleteProtocol = async (protocol: ProtocolItemDO) => {
  ElMessageBox.confirm(
      `确定删除协议 "${protocol.protocolName}" 吗？`,
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(Delete),
      }
  ).then(async () => {
    let res = await deleteProtocolItemById(protocol.id)
    if (res.data.code == 200) {
      message("协议删除成功");
      // 重新获取数据
      await fetchProtocolList();
    } else {
      message("协议删除失败: " + res.data.msg, 'error');
    }

  }).catch(() => {
    // 取消删除
  });
};

// 搜索处理
const handleSearch = () => {
  // 重置当前页码
  currentPage.value = 1;
  // 重新获取数据
  fetchProtocolList();
};

// 新增协议
const handleAddProtocol = () => {
  // mode: 1 新增模式
  handleOpenProtocolEdit(null, 1)
};

// 导入协议
const handleImportProtocol = () => {
  ElMessageBox.prompt('请输入JSON格式的协议数据', '导入协议', {
    inputType: 'textarea',
    inputPlaceholder: '请输入协议JSON字符串',
    confirmButtonText: '导入',
    cancelButtonText: '取消',
    inputValidator: (value) => {
      try {
        JSON.parse(value);
        return true;
      } catch (e) {
        return '请输入有效的JSON字符串';
      }
    }
  }).then(async ({value}) => {
    try {
      const protocolJson: any = JSON.parse(value);
      await saveOrUpdateProtocolItem(protocolJson);
      message('协议导入成功');
      // 重新获取数据
      await fetchProtocolList();
    } catch (error) {
      message('协议导入失败：' + error, 'error');
    }
  }).catch(() => {
    // 取消导入
  });
};

onMounted(async () => {
  await updateCategoryList();
  await fetchProtocolList();

})

// 暴露给父组件的方法
defineExpose({
  handleSearch
})

</script>

<template>
  <div class="protocol-viewer-container">
    <div class="protocol-list-container">
      <div class="list-header">
        <div class="header-left">
          <h2>协议列表</h2>
        </div>
        <div class="header-right">
          <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="起始日期">
              <el-date-picker
                  v-model="searchForm.createTimeBegin"
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择创建日期"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="终止日期">
              <el-date-picker
                  v-model="searchForm.createTimeEnd"
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择创建日期"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="协议名称">
              <el-input
                  v-model="searchForm.protocolName"
                  clearable
                  placeholder="请输入协议名称"
                  style="width: 180px;"
              />
            </el-form-item>
            <el-form-item label="类型码">
              <el-input
                  v-model="searchForm.msgType"
                  clearable
                  placeholder="类型码"
                  style="width: 80px;"
              />
            </el-form-item>
            <el-form-item label="信令码">
              <el-input
                  v-model="searchForm.code"
                  clearable
                  placeholder="信令码"
                  style="width: 80px;"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
            </el-form-item>
          </el-form>
          <div class="action-buttons">
            <el-button v-if="props.showBtn" type="success" @click="handleAddProtocol">新增协议</el-button>
            <el-button v-if="props.showBtn" type="warning" @click="handleImportProtocol">导入协议</el-button>
          </div>
        </div>
      </div>
      <div class="list-content">
        <el-table
            v-loading="loading"
            :data="protocolItems"
            border
            fit
            style="width: 100%"
        >
          <el-table-column label="协议名称" min-width="180" prop="protocolName" show-overflow-tooltip/>
          <el-table-column label="分类" prop="category">
            <template #default="{ row }">
              <span>{{ getCategoryName(row.category) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="消息类型" min-width="100" prop="msgType" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.msgType }} ({{ toHex(row.msgType) }}) </span>
            </template>
          </el-table-column>
          <el-table-column label="信令码" min-width="100" prop="code" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.code }} {{ row.code ? '(' + toHex(row.code) + ')' : '' }} </span>
            </template>
          </el-table-column>
          <el-table-column label="创建人" min-width="100" prop="createNickName" show-overflow-tooltip/>
          <el-table-column label="创建时间" min-width="160" prop="createTime" show-overflow-tooltip/>
          <el-table-column label="修改人" min-width="100" prop="updateNickName" show-overflow-tooltip/>
          <el-table-column label="修改时间" min-width="160" prop="updateTime" show-overflow-tooltip/>
          <el-table-column align="center" fixed="right" label="操作" min-width="120">
            <template #default="scope">
              <el-button
                  v-if="props.showBtn"
                  size="small"
                  type="primary"
                  @click.stop="handleOpenProtocolEdit(scope.row.id)"
              >
                查看
              </el-button>
              <el-button
                  v-if="props.showBtn"
                  size="small"
                  type="danger"
                  @click.stop="deleteProtocol(scope.row)"
              >
                删除
              </el-button>
              <el-button
                  v-if="props.showBtn"
                  size="small"
                  type="success"
                  @click.stop="handleOpenProtocolParse(scope.row.id)"
              >
                解析
              </el-button>
              <el-button
                  v-if="!props.showBtn"
                  size="small"
                  type="primary"
                  @click.stop="handleSelectProtocol(scope.row)"
              >
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 20, 50]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="(page: any) => handlePageChange(page, pageSize)"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.protocol-viewer-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 600px;
}

/* 列表模式样式 */
.protocol-list-container {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
}

.list-header {
  padding: 20px 20px 15px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 50px;
  height: 32px; /* 与按钮和输入框高度保持一致 */
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.list-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
  line-height: 32px; /* 与按钮和输入框高度保持一致 */
  height: 32px;
  display: flex;
  align-items: center;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  margin: 0;
  padding: 0;
}

.search-form :deep(.el-form-item) {
  margin: 0;
  padding: 0;
}

.action-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
}

.list-content {
  flex: 1;
  padding: 15px 20px;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 15px;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
}

/* 确保分页组件始终显示，即使total为0 */
:deep(.el-pagination) {
  display: flex;
  flex-wrap: wrap;
}

:deep(.el-pagination__total) {
  display: block;
}

.header-left {
  display: flex;
  align-items: center;
}


</style>
